package org.coderjonny.exception;

import org.coderjonny.dto.Result;
import org.coderjonny.trace.TraceIdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class RestCtrlExceptionHandler {
	private final Logger logger = LoggerFactory.getLogger(RestCtrlExceptionHandler.class);

	/**
	 * 全局异常处理，统一返回状态码
	 */
	@ExceptionHandler(Exception.class)
	public Result<String> handleException(Exception e) {
		logger.error("服务器抛出了异常：", e);
		return Result.error("error：" + e.getMessage());
	}

	@ExceptionHandler(BusinessException.class)
	public Result<String> handleException(BusinessException e) {
		return Result.error(e.getMessage());
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public Result<String> handleException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        if (!CollectionUtils.isEmpty(allErrors)){
			ObjectError error = allErrors.get(0);
			return Result.error(error.getDefaultMessage());
		}
        logger.error("未知异常：",e);
		return Result.error("未知异常");
	}

}